使用PowerShell建立自簽SSL憑證


Posted by 江馬特 on 2024-02-18

前言

先前使用OpenSSL建立自簽SSL憑證有提到我大部分都在用Windows GUI操作,在沒有外部網路也不給放openssl的時候,要如何野外求生?那就祭出Windows好用的工具PowerShell(使用IIS預設就能產生憑證請求檔與自簽開發用憑證,但很多欄位很難客製設定)!

環境

Windows Server 2019 Standard (1809) - 17763.1637

指令

各項參數就不特別標明應該要怎麼改了,就依照情況變化。

# 子憑證輸出密碼
$certPassword = ConvertTo-SecureString -String "secure" -Force -AsPlainText;
$certFilePath = "Certificate"
# 建立CA
$caparam = @{  
    Subject           = 'C=TW,ST=Taiwan,L=Taipei,O=Demo,OU=IT,CN=Demo Develop CA,E=nobody@demo.net'  
    KeyUsage          = @("CertSign", "CrlSign")  
    CertStoreLocation = 'Cert:\LocalMachine\My'  
    TextExtension     = @('2.5.29.19={text}CA=true&pathlength=0')  
    HashAlgorithm     = "SHA256"  
    NotAfter          = (Get-Date).AddYears(20)  
    KeyAlgorithm      = "RSA"  
    KeyLength         = 4096  
    FriendlyName      = "DemoCA"  
}  

$rootCa = New-SelfSignedCertificate @caparam;  

# 建立憑證參數  
$paramsCert = @{  
    Type              = 'Custom'  
    Subject           = 'C=TW,ST=Taiwan,L=Taipei,O=ESi,OU=IT,CN=Demo Develop Cert,E=nobody@demo.net'  
    KeyUsage          = @('DigitalSignature', 'DataEncipherment', 'KeyEncipherment')  
    TextExtension     = @(  
        '2.5.29.37={text}1.3.6.1.5.5.7.3.2,1.3.6.1.5.5.7.3.1',  
        '2.5.29.17={text}DNS=*.demo.net&DNS=localhost&IPAddress=127.0.0.1&IPAddress=::1' )  
    KeyAlgorithm      = 'RSA'  
    KeyLength         = 4096  
    KeyExportPolicy   = "Exportable"  
    CertStoreLocation = 'Cert:\LocalMachine\My'  
    NotAfter          = (Get-Date).AddYears(20)  
    Signer            = $rootCa;  
    FriendlyName      = "Demo 開發憑證"  
}  

# 建立自簽憑證  
$selfSign = New-SelfSignedCertificate @paramsCert;  

# 移動CA憑證到可信任的位置  
$rootCa | Move-Item -Destination "Cert:\LocalMachine\Root";  

New-Item -Path $certFilePath -ItemType Directory -Force

# 產出憑證檔案  
Export-PfxCertificate -Cert $selfSign -FilePath "$certFilePath\server.pfx" -Password $certPassword  
Export-PfxCertificate -Cert $rootCa -FilePath "$certFilePath\ca.pfx" -Password $certPassword;

可以在本機憑證中找到對應憑證
產出結果圖

動作

其實意外的相當簡單,比製作憑證請求檔(CSR)還要簡單得多

  1. 準備一組輸出密碼,提供最後憑證都做完後輸出使用
  2. 準備輸出PFX的路徑資料夾(單純只是方便IIS使用)
  3. 建立CA憑證
  4. 用CA憑證簽立自簽憑證
  5. 將憑證都移到該去的地方
  6. 將憑證產出到指定位置

結語

本篇只是做一個快速的筆記紀錄,其實目前大部分軟體都可以看到自簽憑證的項目,實務上其實也不算常碰到需要自己簽的狀況,所以還有一些需要注意的地方在這裡沒有特別指出來。
例如:CA憑證在製作完成後,雖然被放進「受信任的根憑證授權單位」,但是仔細一看就會發現自己簽出來的憑證比其它張憑證多了個鎖頭,也就是憑證上包含了該張憑證的key,如果取得這張憑證時,是可以再以這張憑證多簽出幾張憑證來的。如果說要排除這個問題,可以將已安裝的憑證刪除,透過重新匯入自簽PFX檔案,來移除CA上的key。又或者單純開發使用時,其實不用這麼麻煩特別將CA自己一張,將自簽憑證同時放在「個人」與「受信任的根憑證授權單位」也是一個方法。

參考

  1. 如何使用 PowerShell 建立開發測試用途的自簽憑證 (Self-Signed Certificate)
  2. New-SelfSignedCertificate

#powershell #New-SelfSignedCertificate #SSL憑證 #自簽憑證







Related Posts

後端軟體工程工具箱:資料庫/SQL/ORM篇

後端軟體工程工具箱:資料庫/SQL/ORM篇

MTR04_0910

MTR04_0910

OpenCV在空拍影像中單一辨識顏色

OpenCV在空拍影像中單一辨識顏色


Comments